package com.zhkj.txg.module.order.ui

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.entity.node.BaseNode
import com.google.gson.Gson
import com.zhkj.lib.base.BalanceChangeEvent
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.order.adapter.OrderDetailAdapter
import com.zhkj.txg.module.order.entity.*
import com.zhkj.txg.module.order.popup.OrderReceivePopupWindow
import com.zhkj.txg.module.order.popup.PayTypePopupWindow
import com.zhkj.txg.module.order.vm.OrderViewModel
import com.zhkj.txg.module.product.popup.ProductSharePopupWindow
import com.zhkj.txg.module.product.ui.ProductShareActivity
import com.zhkj.txg.utils.*
import kotlinx.android.synthetic.main.activity_order_status_detail.*

class OrderDetailActivity : ViewModelActivity<OrderViewModel>() {

    companion object {
        private val ORDER_ID = "orderId"
        private val ORDER_SN = "orderSn"
        private val ORDER_GROUP = "ORDER_GROUP"//拼团订单

        fun open(context: Context, orderId: Long, orderSn: String, isGroup: Boolean = false) {
            val intent = Intent(context, OrderDetailActivity::class.java)
                .putExtra(ORDER_ID, orderId)
                .putExtra(ORDER_SN, orderSn)
            if (isGroup) {
                intent.putExtra(ORDER_GROUP, isGroup)
            }
            context.startActivity(intent)
        }

        fun open(context: Context, orderId: Long, isGroup: Boolean = false) {
            val intent = Intent(context, OrderDetailActivity::class.java)
                .putExtra(ORDER_ID, orderId)
            if (isGroup) {
                intent.putExtra(ORDER_GROUP, isGroup)
            }
            context.startActivity(intent)
        }
    }

    var isGroup: Boolean = false
    override fun setViewModel(): OrderViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleOrderDetail
    override val layoutResId: Int = R.layout.activity_order_status_detail

    private val detailAdapter = OrderDetailAdapter {
        // 根据退款状态判断跳转页面
        when (it.refundStatus) {
            0 -> OrderChooseTypeActivity.start(this, intent.getLongExtra(ORDER_ID, 0), it.goodsId, isGroup)
            else -> OrderRefundDetailActivity.open(
                this, 0, intent.getLongExtra(ORDER_ID, 0), it.goodsId, requestCodeUndo, isGroup
            )
        }
    }
    private val requestCodeUndo = 1092

    // 选择支付方式的popup
    private val payTypePopupWindow: PayTypePopupWindow by lazy {
        PayTypePopupWindow(this, { type, orderInfo ->
            viewModel.payOrder(
                AccountManager.getToken(), orderInfo.orderId,
                orderInfo.orderSignNumber, type, orderInfo.uiPosition, isGroup
            )
        }, { false })
    }

    // 确认收货的popup
    private val receivePopupWindow: OrderReceivePopupWindow by lazy {
        OrderReceivePopupWindow(this) { uiPosition, orderId ->
            viewModel.receiveOrder(AccountManager.getToken(), uiPosition, orderId, isGroup)
        }
    }

    override fun initUI() {
        with(rvOrderDetail) {
            layoutManager = LinearLayoutManager(this@OrderDetailActivity)
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            adapter = detailAdapter
        }
        // 取消订单
        tvOrderListCancel.setOnClickListener {
            viewModel.cancelOrder(AccountManager.getToken(), intent.getLongExtra(ORDER_ID, 0), 0, isGroup)
        }
        // 查看物流
        tvOrderListShipping.setOnClickListener {
            OrderShippingActivity.start(this, intent.getLongExtra(ORDER_ID, 0), isGroup)
        }
        // 确认收货
        tvOrderListConfirm.setOnClickListener {
            receivePopupWindow.setData(0, intent.getLongExtra(ORDER_ID, 0))
            receivePopupWindow.showPopupWindow()
        }
        // 核销码
        tvOrderListWriteOffCode.setOnClickListener {
            val orderSn = intent.getStringExtra(ORDER_SN)
            layDialog(
                "订单号:${orderSn}",
                QRCodeUtils.createQRCodeBitmap(orderSn, 700, 700)
            )
        }
        // 立即支付
        tvOrderListPay.setOnClickListener {
            viewModel.orderDetailLiveData.value?.response?.data?.let {
                val entity = OrderSubmitEntity(
                    it.totalAmount.toDouble(),
                    it.orderSignNumber
                ).apply {
                    orderId = it.id
                }
                showPayPopup(entity)
            }
        }
        // 跳转评论页面
        tvOrderListEvaluate.setOnClickListener {
            viewModel.orderDetailLiveData.value?.response?.data?.let {
                OrderEvaluatePublishActivity.open(this, it.id, it.orderGoods, isGroup)
            }
        }
        tvOrderListDelete.setOnClickListener {
            viewModel.deleteOrder(intent.getLongExtra(ORDER_ID, 0), isGroup = isGroup)
        }
        text_share.setOnClickListener {
            with(sharePopupWindow) {
                val tempEntity = viewModel.orderDetailLiveData.value?.response?.data
                tempEntity?.orderGoods?.get(0)?.let {
                    setQRcode(View.GONE)
                    productName = it.goodsName
                    productPrice = it.goodsPrice
                    productImage = mutableListOf(it.image)
                    goodsId = it.goodsId
                    shareUrl = tempEntity.share_url
                    showPopupWindow()
                }
            }
        }
    }

    private val sharePopupWindow: ProductSharePopupWindow by lazy {
        ProductSharePopupWindow(this) { type ->
            when (type) {
                2 -> {
                    if (sharePopupWindow.productImage.isNotEmpty()) ProductShareActivity.open(
                        this, sharePopupWindow.goodsId,
                        sharePopupWindow.productImage.toTypedArray(),
                        sharePopupWindow.productName,
                        sharePopupWindow.productPrice
                    ) else toast(getString(R.string.empty_gallery))
                }
                1 -> ShareUtils.shareUrl2Friends(
                    this,
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl
                )
                else -> ShareUtils.shareUrl2Friends(
                    this,
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl,
                    true
                )
            }
        }
    }

    override fun initViewModel() {
        isGroup = intent.getBooleanExtra(ORDER_GROUP, false)
        // 倒计时LiveData观察
        viewModel.countDownLiveData.observe(this, Observer {
            detailAdapter.notifyItemChanged(detailAdapter.itemCount - 2)
        })

        // 微信支付结果观察者
        viewModel.payResult().observe(this, Observer {
            if (it.paySuccess) {
                paySuccess()
            } else toast(it.payDesc)
        })
        // 取消订单结果观察者
        viewModel.orderCancelLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                toast(it.msg ?: getString(R.string.order_cancel_success))
                // 通知列表页，需要进行刷新
                RxBus.post(OrderListRefreshEvent(listOf(Type.ALL)))
                // 重新请求数据
                initData()
            }
        })
        // 订单状态刷新观察者
        viewModel.orderListStatusSubscribe().observe(this, Observer {
            if (it.refreshType.contains(Type.COMPLETE)) {
                viewModel.orderDetail(AccountManager.getToken(), intent.getLongExtra(ORDER_ID, 0), isGroup)
            }
        })
        // 订单确认收货观察者
        viewModel.receiveOrderLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                toast(it.msg ?: getString(R.string.order_receive_success))
                // 通知列表页，需要刷新数据
                RxBus.post(
                    OrderListRefreshEvent(listOf(Type.ALL, Type.SEND, Type.RECEIVE, Type.COMPLETE))
                )
                // 刷新数据
                initData()
            }
        })
        // 订单支付观察者
        viewModel.payOrderLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { order ->
                if (!order.isNeedPay) {
                    // 刷新个人中心余额
                    RxBus.post(BalanceChangeEvent())
                    paySuccess()
                } else when (order.payType) {
                    // 微信支付
                    OrderPayEntity.TYPE_WECHAT -> {
                        order.payInfo.let {
                            val entity = Gson().fromJson(it, WXPayEntity::class.java)
                            PayUtils.wxPay(this, entity, order.uiPosition)
                        }
                    }
                    // 支付宝支付
                    OrderPayEntity.TYPE_ALIPAY -> PayUtils.aliPay(this, order.payInfo, { paySuccess() }, { toast(it) })
                    else -> Unit
                }
            }
        })
        // 删除订单观察者
        viewModel.deleteOrderLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                toast(response?.response?.msg ?: getString(R.string.delete_success))
                RxBus.post(OrderListRefreshEvent(listOf(Type.ALL)))
                finish()
            }
        })
        // 订单详情数据观察者
        viewModel.orderDetailLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                it.status = it.progress?.status ?: 0
                tvOrderDetailPrice.text = SpanUtil.setPrefixMoneyStr("合计:", it.orderAmount)
                detailAdapter.data.clear()
                // 添加状态模块
                val statusEntity =
                    if (!isGroup) createStatusEntityAndButton(it.orderStatus, it.shippingStatus, it.payStatus)
                    else createStatusEntityAndButtonGroup(
                        it.orderStatus,
                        it.shippingStatus,
                        it.payStatus,
                        it.status ?: 0
                    )
                detailAdapter.addData(statusEntity)
                // 添加物流模块(TODO 请求物流信息接口)
//                detailAdapter.addData(
//                    OrderDetailUIShippingEntity(
//                        it.shippingCode,
//                        it.shippingName,
//                        it.shippingNumber,
//                        ""
//                    )
//                )
                // 添加地址模块
                if (!it.fullAddress.isNullOrEmpty()) {
                    detailAdapter.addData(
                        OrderDetailUIAddressEntity(
                            it.consignee,
                            mobile = it.mobile,
                            address = it.fullAddress
                        )
                    )
                }
                // 添加店铺信息
//                (it.shops as? BaseNode)?.let { shop -> detailAdapter.addData(shop) }
                // 添加商品信息
                it.orderGoods.forEach { goods ->
                    goods.showRefundButton = statusEntity.showRefundButton
                    goods.isGroup = isGroup
                }
                detailAdapter.addData(it.orderGoods)
                // 添加价格信息
                detailAdapter.addData(
                    OrderDetailPriceUIEntity(it.shippingPrice, it.couponPrice, it.orderAmount)
                )
                // 拼团进度
                if (isGroup && it.progress?.status == 10) {
                    it.progress?.let { it1 -> detailAdapter.addData(it1) }
                    viewModel.startCountDown()
                }
                // 添加订单信息
                detailAdapter.addData(OrderDetailUIEntity(it.orderInfo))
            }
        })
    }

    override fun initData() {
        viewModel.orderDetail(AccountManager.getToken(), intent.getLongExtra(ORDER_ID, 0), isGroup)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == requestCodeUndo) initData()
    }

    private fun paySuccess() {
        toast(getString(R.string.pay_success))
        payTypePopupWindow.dismiss()
        // 通知列表页，需要刷新
        RxBus.post(OrderListRefreshEvent(listOf(Type.ALL, Type.PAY, Type.SEND)))
        // 支付成功，刷新页面
        initData()
    }

    /**
     * 生成订单状态的Entity，并设置底部按钮的显示
     */
    private fun createStatusEntityAndButton(
        orderStatusStr: String,
        shippingStatusStr: String,
        payStatusStr: String
    ): OrderDetailStatusEntity {
        val orderStatus = orderStatusStr.toInt()
        val payStatus = payStatusStr.toInt()
        val shippingStatus = shippingStatusStr.toInt()
        // 订单已取消
        val isStatusCancel = orderStatus == 3 || orderStatus == 6
        // 收货之前并且未付款,即未付款
        val isStatusNotPay = orderStatus < 2 && payStatus == 0
        // 收货之前，已付款，未发货，即待发货
        val isStatusNotSend = payStatus == 1 && shippingStatus == 0 && orderStatus < 2
        // 收货之前，已发货，未退款，即待收货
//        val isStatusReceive = orderStatus < 2 && shippingStatus == 1 && payStatus != 3
        val isStatusReceive = orderStatus == 5
        // 已收货，未评价
        val isStatusNotCommit = orderStatus == 2
        // 已完成，已评价，未退款，即已完成
        val isStatusComplete = orderStatus == 4

        tvOrderListCancel.visibility = View.GONE
        tvOrderListShipping.visibility = View.GONE
        tvOrderListPay.visibility = View.GONE
        tvOrderListConfirm.visibility = View.GONE
        tvOrderListEvaluate.visibility = View.GONE
        tvOrderListWriteOffCode.visibility = View.GONE
        tvOrderListDelete.visibility = View.GONE
        return when {
            isStatusCancel -> {
                viewButton.visibility = View.VISIBLE
                tvOrderListDelete.visibility = View.VISIBLE
                OrderDetailStatusEntity(0, getString(R.string.order_status_cancel))
            }
            isStatusNotPay -> {
                tvOrderListPay.visibility = View.VISIBLE
                tvOrderListCancel.visibility = View.VISIBLE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_wait_pay,
                    getString(R.string.order_non_payment),status = 1
                )
            }
            isStatusNotSend -> {
//                tvOrderListConfirm.visibility = View.VISIBLE
//                viewButton.visibility = View.GONE
                tvOrderListWriteOffCode.visibility = View.VISIBLE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_payed,
                    getString(R.string.non_delivery), true,status = 2
                )
            }
            isStatusReceive -> {
                tvOrderListConfirm.visibility = View.VISIBLE
//                tvOrderListShipping.visibility = View.VISIBLE
                tvOrderListWriteOffCode.visibility = View.VISIBLE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_waite_receive,
                    getString(R.string.non_receive), true,status = 3
                )
            }
            isStatusNotCommit -> {
                tvOrderListEvaluate.visibility = View.GONE
                tvOrderListWriteOffCode.visibility = View.VISIBLE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_complete,
                    getString(R.string.order_complete), true,status = 4
                )
            }
            isStatusComplete -> {
                tvOrderListEvaluate.visibility = View.GONE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_complete,
                    getString(R.string.order_complete), true,status = 4
                )
            }
            else -> OrderDetailStatusEntity(0, getString(R.string.order_status_unknown))
        }
    }

    /**
     * 拼团中：生成订单状态的Entity，并设置底部按钮的显示
     */
    private fun createStatusEntityAndButtonGroup(
        orderStatusStr: String,
        shippingStatusStr: String,
        payStatusStr: String,
        status: Int //拼团状态  0单买 10拼单中 20拼单成功 30拼单失败
    ): OrderDetailStatusEntity {
        val orderStatus = orderStatusStr.toInt()
        val payStatus = payStatusStr.toInt()
        val shippingStatus = shippingStatusStr.toInt()
        // 订单已取消
        val isStatusCancel = orderStatus == 3
        // 收货之前并且未付款,即未付款
        val isStatusNotPay = orderStatus < 2 && payStatus == 0
        // 收货之前，已付款，未发货，即待发货
        val isStatusNotSend = payStatus == 1 && shippingStatus == 0 && orderStatus < 2
        // 收货之前，已发货，未退款，即待收货
        val isStatusReceive = orderStatus < 2 && shippingStatus == 1 && payStatus != 3
        // 已收货，未评价
        val isStatusNotCommit = orderStatus == 2
        // 已完成，已评价，未退款，即已完成
        val isStatusComplete = orderStatus == 4

        tvOrderListPay.visibility = View.GONE
        tvOrderListCancel.visibility = View.GONE
        tvOrderListConfirm.visibility = View.GONE
        tvOrderListShipping.visibility = View.GONE
        tvOrderListEvaluate.visibility = View.GONE
        tvOrderListDelete.visibility = View.GONE
        text_share.visibility = View.GONE

        return when {
            status == 30 -> {
                tvOrderListDelete.visibility = View.VISIBLE
                OrderDetailStatusEntity(0, getString(R.string.group_fail_desc))
            }
            isStatusNotPay -> {
                tvOrderListPay.visibility = View.VISIBLE
                tvOrderListCancel.visibility = View.VISIBLE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_wait_pay,
                    getString(R.string.order_non_payment)
                )
            }
            status == 10 -> {
                text_share.visibility = View.VISIBLE
                OrderDetailStatusEntity(0, getString(R.string.group_ing), true)
            }
            isStatusCancel -> {
                viewButton.visibility = View.VISIBLE
                tvOrderListDelete.visibility = View.VISIBLE
                OrderDetailStatusEntity(0, getString(R.string.order_status_cancel))
            }
            isStatusNotSend -> {
//                tvOrderListConfirm.visibility = View.VISIBLE
                viewButton.visibility = View.GONE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_payed,
                    getString(R.string.non_delivery), true
                )
            }
            isStatusReceive -> {
                tvOrderListConfirm.visibility = View.VISIBLE
                tvOrderListShipping.visibility = View.VISIBLE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_waite_receive,
                    getString(R.string.non_receive), true
                )
            }
            isStatusNotCommit -> {
                tvOrderListEvaluate.visibility = View.VISIBLE
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_complete,
                    getString(R.string.order_complete), true
                )
            }
            isStatusComplete -> {
                OrderDetailStatusEntity(
                    R.drawable.ic_order_status_complete,
                    getString(R.string.order_complete), true
                )
            }
            else -> OrderDetailStatusEntity(0, getString(R.string.order_status_unknown))
        }
    }

    /**
     * 显示支付按钮
     * @param it 数据对象，包含金额、订单号、订单ID、订单对应的列表位置
     */
    private fun showPayPopup(it: OrderSubmitEntity) {
        payTypePopupWindow.run {
            setData(it)
            showPopupWindow()
        }
    }


    /**
     * 自定义布局的对话框
     */
    private fun layDialog(title: String, content: Bitmap?) {
        val view: View = LayoutInflater.from(this).inflate(
            R.layout.dialog_coupon_qr, null, false
        )
        val dialog = Dialog(this)
        dialog.setContentView(view)
        dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
        val tvCouponCode: TextView = view.findViewById(R.id.tvCouponCode)
        val ivCouponQR: ImageView = view.findViewById(R.id.ivCouponQR)
        tvCouponCode.text = title
        if (content == null) {
            ivCouponQR.visibility = View.GONE
            toast("二维码生成错误")
        } else {
            ivCouponQR.visibility = View.VISIBLE
            ivCouponQR.setImageBitmap(content)
        }
        dialog.show()
    }
}